package com.cskaoyan.servlet;

import com.cskaoyan.bean.MarketCoupon;
import com.cskaoyan.bean.common.BaseRespVo;
import com.cskaoyan.bean.common.CommonData;
import com.cskaoyan.service.CouponService;
import com.cskaoyan.service.CouponServiceImpl;
import com.cskaoyan.util.JacksonUtil;
import com.cskaoyan.util.ResponseUtil;
import com.cskaoyan.util.StringUtil;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author stone
 * @date 2023/03/20 11:44
 */
@WebServlet("/admin/coupon/*")
public class AdminCouponServlet extends WdBaseServlet {

    private CouponService couponService = new CouponServiceImpl();

    @Override
    protected void handle(String operation, HttpServletRequest request, HttpServletResponse response) throws IOException {
        switch (operation) {
            case "/list":
                list(request, response);
                break;
            case "/create":
                create(request, response);
                break;
        }
    }

    private void create(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String jsonStr = request.getReader().readLine();
        MarketCoupon coupon = JacksonUtil.read(jsonStr, MarketCoupon.class);
        BaseRespVo baseRespVo = couponService.create(coupon);
        ResponseUtil.responseJson(response, baseRespVo);
    }

    private void list(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String name = request.getParameter("name");
        String typeStr = request.getParameter("type");
        Short type = StringUtil.isNotEmpty(typeStr)?Short.parseShort(typeStr):null;
        Short status = StringUtil.isNotEmpty(request.getParameter("status"))?Short.parseShort(request.getParameter("status")):null;
        Integer page = StringUtil.isNotEmpty(request.getParameter("page"))?Integer.parseInt(request.getParameter("page")):null;
        Integer limit = StringUtil.isNotEmpty(request.getParameter("limit"))?Integer.parseInt(request.getParameter("limit")):null;
        String sort = request.getParameter("sort");
        String order = request.getParameter("order");
        CommonData<MarketCoupon> data = couponService.querySelective(name, type, status, page, limit, sort, order);
        ResponseUtil.responseJson(response, BaseRespVo.ok(data));
    }
}
